1287D - Numbers on Tree - CodeForces Solution


constructive algorithms data structures dfs and similar graphs trees *1800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
template<class T> inline void read(T &x){
	x=0;register char c=getchar();register bool f=0;
	while(!isdigit(c))f^=c=='-',c=getchar();
	while(isdigit(c))x=x*10+c-'0',c=getchar();if(f)x=-x;
}
template<class T> inline void print(T x){
	if(x<0)putchar('-'),x=-x;
	if(x>9)print(x/10);putchar(x%10+'0');
}
template<class T> inline void print(T x,char c){print(x),putchar(c);}
template<class T> inline void print(T a,int l,int r){for(int i=l;i<=r;i++)print(a[i]," \n"[i==r]);}
const int N=4010;
int n,m,siz[N],c[N],res[N],vis[N];
std::vector<int> son[N];
void dfs1(int u){
	siz[u]=1;
	for(int v:son[u])dfs1(v),siz[u]+=siz[v];
}
void dfs2(int u){
	for(int c=0,lst=::c[u];;){
		++c;
		if(!vis[c]){
			if(lst)--lst;
			else{
				res[u]=c;
				vis[c]=1;
				break;
			}
		}
	}
	for(int v:son[u])dfs2(v);
}
int main(){
#ifdef memset0
	freopen("1.in","r",stdin);
#endif
	read(n);
	for(int p,i=1;i<=n;i++){
		read(p),read(c[i]);
		son[p].push_back(i);
	}
	dfs1(son[0][0]);
	// for(int i=1;i<=n;i++)print(siz[i]," \n"[i==n]);
	for(int i=1;i<=n;i++)if(c[i]>=siz[i]){
		puts("NO");
		return 0;
	}
	dfs2(son[0][0]);
	puts("YES");
	for(int i=1;i<=n;i++)print(res[i]," \n"[i==n]);
}


Comments

Submit
0 Comments
More Questions

1356. Sort Integers by The Number of 1 Bits
922. Sort Array By Parity II
344. Reverse String
1047. Remove All Adjacent Duplicates In String
977. Squares of a Sorted Array
852. Peak Index in a Mountain Array
461. Hamming Distance
1748. Sum of Unique Elements
897. Increasing Order Search Tree
905. Sort Array By Parity
1351. Count Negative Numbers in a Sorted Matrix
617. Merge Two Binary Trees
1450. Number of Students Doing Homework at a Given Time
700. Search in a Binary Search Tree
590. N-ary Tree Postorder Traversal
589. N-ary Tree Preorder Traversal
1299. Replace Elements with Greatest Element on Right Side
1768. Merge Strings Alternately
561. Array Partition I
1374. Generate a String With Characters That Have Odd Counts
1822. Sign of the Product of an Array
1464. Maximum Product of Two Elements in an Array
1323. Maximum 69 Number
832. Flipping an Image
1295. Find Numbers with Even Number of Digits
1704. Determine if String Halves Are Alike
1732. Find the Highest Altitude
709. To Lower Case
1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings